package cn.iocoder.yudao.module.system.controller.admin.mail;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.EmailInfo;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.encryption.EncryptionUtil;
import cn.iocoder.yudao.framework.common.util.mail.MailUtils;
import cn.iocoder.yudao.module.member.api.company.CompanyApi;
import cn.iocoder.yudao.module.student.api.student.StudentApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.redis.mail.MailRedisDAO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.CODE_NOT_EXISTS;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS;

@Api(tags = "管理后台 -身份验证- 邮件验证")
@RestController
@RequestMapping("/system/mail")
@Validated
@Log4j2
public class MailController {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    @Resource
    private MailRedisDAO mailRedisDAO;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private CompanyApi companyApi;
    @Resource
    private StudentApi studentApi;
    @GetMapping("/verification")
    @ApiOperation("邮箱验证")
    public CommonResult<Boolean> verification(@RequestParam("code")String code,@RequestParam("tag")String tag,@RequestParam("type")String type) {
        String phone=EncryptionUtil.desDecrypt(tag);
        String scode=mailRedisDAO.get(phone);
        log.info("scode="+scode+"==========code="+code);
        if(scode==null&&!scode.equals(code)) {
            throw exception(CODE_NOT_EXISTS);
        }
        if(scode.equals(code)){
            if(type.equals("student")){
                studentApi.isAuthorizedId(phone);
                return success(true);
            }else {
                AdminUserRespDTO adminUserRespDTO= userApi.getNoTenantUser(phone);
                Long companyId=adminUserRespDTO.getCompanyId();
                if(companyId!=null) {
                    companyApi.isAuthenticationId(companyId);
                    return success(true);
                }
            }
            return success(true);
        }else {
            return success(false);
        }
    }


    @GetMapping("/send")
    @ApiOperation("邮箱验证发送")
    public CommonResult<Boolean> send(@RequestParam("recevices") String recevices,  @RequestParam("name")String name,@RequestParam("tag")String tag,@RequestParam("type")String type) {
        String code =MailUtils.codeFen();
        try {
            String str = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>亲爱的："+name+"，您好！</p>"
                    + "<p style='text-align:right; padding-right: 20px;'>请复制下方网页地址到浏览器地址栏中打开，完成邮箱验证：</p>"
                    + "<p style='text-align:right; padding-right: 20px;'> https://www.datarer.com/admin-api/system/mail/verification?type="+type+"&code="+code+"&tag="+ EncryptionUtil.desEncrypt(tag)
                    + "<a href='https://www.datarer.com/admin-api/system/mail/verification?code='"+code+"&tag="+ EncryptionUtil.desEncrypt(tag)+" style='font-size: 18px'>(认证链接)</a></p>"
                    + "<p style='text-align:; font-size: 18px; padding-right: 20px;'> 该链接有效期至"+ DateUtils.addDay(new Date(),1) +"请尽快认证</p>"
                    + "<p style='text-align:right; padding-right: 20px;'> " + sdf.format(new Date()) + "</p></body></html>";
            EmailInfo emailInfo=new EmailInfo();
            emailInfo.setToUser(recevices);
            emailInfo.setSubject("【数据学徒】请完成邮箱验证");
            emailInfo.setContent(str);
            mailRedisDAO.set(tag,code,Duration.ofDays(1));
//            MailUtils.sendHtmlMail(emailInfo);
            userApi.sendHtmlMail(emailInfo);

        }catch (Exception e){
           e.printStackTrace();
        }
        return  success(true);
    }




}
